package com.ysz.component.log;

import com.ysz.component.constant.MyBatisConst;
import com.ysz.component.statisticstime.StatisticsTime;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.*;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @ClassName LogInterceptor
 * @Description TODO
 * @Data 10:06
 * @Version 1.0
 * @Author ysz
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        //@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MyBatisLogInterceptor implements Interceptor {

    private boolean enableTraceWatch;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            //获取被执行的sqlId
            String id = mappedStatement.getId();
            //获取sql
            BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
            Object proceed = null;
            if (enableTraceWatch) {
                try (StatisticsTime statisticsTime = new StatisticsTime(id)) {
                    statisticsTime.start(id);
                    proceed = invocation.proceed();
                } catch (Exception e) {
                    e.printStackTrace();
                    return invocation.proceed();
                }
            }
            System.out.println(getSql(mappedStatement, boundSql, id));
            return proceed;
        } catch (Exception e) {
            e.printStackTrace();
            return invocation.proceed();
        }
    }

    public String getSql(MappedStatement mappedStatement, BoundSql boundSql, String id) {
        Configuration configuration = mappedStatement.getConfiguration();
        return "sql:" + id + "任务拼装sql语句最终结果是： " + assembleSql(configuration, boundSql);
    }


    public String assembleSql(Configuration configuration, BoundSql boundSql) {
        //获取mapper上的参数  接口参数
        Object parameterObject = boundSql.getParameterObject();
        //获取sql实际用到的参数  sql参数
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql();
        if (Objects.nonNull(parameterMappings) && parameterMappings.size() > 0) {
            MetaObject metaObject = configuration.newMetaObject(parameterObject);
            for (ParameterMapping mapping : parameterMappings) {
                String property = mapping.getProperty();
                if (metaObject.hasGetter(property)) {
                    sql = sql.replace("?", parseValue(metaObject.getValue(property)));
                }
            }
        }
        return sql;
    }


    public String parseValue(Object value) {
        if (value instanceof Date) {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sim.format((Date) value);
            return "#{" + format + "}";
        } else {
            return "#{" + value.toString() + "}";
        }
    }


    @Override
    public Object plugin(Object target) {
        return target instanceof Executor ? Plugin.wrap(target, this) : target;
    }


    @Override
    public void setProperties(Properties properties) {
        this.enableTraceWatch = Boolean.parseBoolean(properties.getProperty(MyBatisConst.sql_trace_watch.getKey()));
    }
}
